(function () {
	const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
	const ws = new WebSocket(`${protocol}://${location.host}`);

	const selfEl = document.getElementById('self');
	const onlineEl = document.getElementById('online');
	const messagesEl = document.getElementById('messages');
	const formEl = document.getElementById('form');
	const inputEl = document.getElementById('input');

	function addMessage({ type, from, text, ts }) {
		const li = document.createElement('li');
		const time = ts ? new Date(ts).toLocaleTimeString() : '';
		if (type === 'chat') {
			li.innerHTML = `<span class="time">${time}</span><span class="name">${from.name}:</span> <span class="text"></span>`;
			li.querySelector('.text').textContent = text;
		} else if (type === 'system') {
			li.className = 'system';
			li.textContent = text;
		}
		messagesEl.appendChild(li);
		messagesEl.scrollTop = messagesEl.scrollHeight;
	}

	function renderOnline(list) {
		onlineEl.innerHTML = '';
		(list || []).forEach(u => {
			const li = document.createElement('li');
			li.textContent = u.name;
			onlineEl.appendChild(li);
		});
	}

	ws.addEventListener('message', (event) => {
		let data;
		try { data = JSON.parse(event.data); } catch { return; }
		if (data.type === 'welcome') {
			selfEl.textContent = `我的昵称：${data.self.name}`;
			renderOnline(data.online);
		} else if (data.type === 'system') {
			addMessage({ type: 'system', text: data.text });
			renderOnline(data.online);
		} else if (data.type === 'chat') {
			addMessage(data);
		}
	});

	formEl.addEventListener('submit', (e) => {
		e.preventDefault();
		const text = inputEl.value.trim();
		if (!text) return;
		ws.readyState === WebSocket.OPEN && ws.send(JSON.stringify({ type: 'chat', text }));
		inputEl.value = '';
	});
})();
